var app = getApp();
var util = require('../../../../utils/util.js');
import {date,years,months,days,today} from '../../../../utils/date';
const limit_test=50;  //默认限制50条
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isJieKuan: false, //生成结款单弹窗
    shop_ids: [],
    isChooseAll: false, //全选
    is_checked: {},   //单选
    isclasscheck: {}, //类选是否选中
    checkCount: 0, //选中几份
    total_money: 0, //合计价格
    jk_total:0,  //账单合计
    bill_name:'',//结款单名称
    limit:limit_test,
    typename: ['待对账','对账中','待结款','完成','询价'],
    active:-1,  //展示列表的初始索引值;0未结订单，1结款单
    paymentList: [],  //结款单列表
    screen_area_list:['今天','昨天','当月单'],
    z_screen_area_index:-1,
    screen_area_index:-1,
    area_time:0, //时间段开始时间
    is_screen:false,  //筛选下拉
    // 时间周期********
    years,
    year: date.getFullYear(),
    months:months,
    month: 2,
    days:days,
    day: 2,
    value: [date.getFullYear() - 2010, date.getMonth(), date.getDate() - 1],  //默认今天
    time_type: 0,  //时间time切换的初始索引值
    start_time: 0,  //开始时间
    today:today, //今天
    end_time:today,    //结束时间,默认今天
    z_start_time:0, //选择开始时间
    z_end_time:today,   //选择结束时间,默认今天
    c_start_time: 0,  //右窗开始时间
    c_end_time:today, //结束时间,默认今天
    // *****
    is_read_count1:0,  //待对账数量
    is_read_count2:0,  //对账中数量
    is_read_count3:0  //待结款数量
  },
  // 去供应商详情页面
  tosupperdetail: function () {
    if (this.data.authType == "manage_finance") {
      console.log(this.data.id)
      wx.navigateTo({
        url: '/pages/wo/gongyingshangguanli/gongyingshangdetail/gongyingshangdetail?id=' + this.data.id
      })
    }
  },
  // 打电话
  call_phone:function(e){
    if(app.globalData.test==1){
      wx.showLoading({
        title: '暂无权限',
        duration: 500
      });
      return;
    };
    wx.makePhoneCall({
      phoneNumber: this.data.rightDatas.phone
    })
  },
  // 切换状态
  myselect: function(e) {
    console.log(e.currentTarget.dataset.id);
    var active=e.currentTarget.dataset.id;
    this.setData({
      active:active,
      loading:1,
      limit:limit_test
    });
    if (active <= 0){    //未结订单 
      this.paymentList();  
      this.nosettle(); 
    }else if (active>=1 && active<=3){  //结款单
      this.nosettle(); 
      this.paymentList(); 
    }else if(active==4){  //询价记录
      this.paymentList();  
      this.off_history();
    };
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    console.log(options);
    that.setData({
      loginInfo:app.globalData.loginInfo,
      is_zi_cai:options.is_zi_cai,
      group_id: app.globalData.group_id,  //是否绑定了集团码
      id: options.id,
      rightDatas: JSON.parse(options.val)
    });
    console.log(that.data.rightDatas.logo)
    // 获取当前用户身份
    app.AppHttp('api/Order/personalAuthType', {
      openid: app.globalData.openid
    }, function (res) {
      console.log(JSON.stringify(res.data));
      that.setData({
        authType: res.data.type
      })
    });
  },
  noneEnoughPeople:function(){
    return;
  },
  // 对账单列表 
  paymentList: function() {
    let that = this;
    wx.showLoading({
      title: '加载中...',
    })
    app.AppHttp('api/Order/paymentList', {
      openid: app.globalData.openid,
      supplier_id: that.data.id
    }, function(res) {
      console.log(JSON.stringify(res.data));  
      var jk_total=0;
      var is_read_count2=0;
      var is_read_count3=0; 
      var paymentList=[];
      if(res.data.length>0){
        paymentList = res.data.filter(function (item) {
          if(item.status==0){
            is_read_count2++;
          }else if(item.status==1 && item.is_one_one==1){
            is_read_count3++;
          };
          if(item.status==that.data.active-1){
            jk_total+=item.total_amount*1;
            return item.status==0 ||  item.status>=1 && item.is_one_one==1;
          };
        });
      };
      that.setData({
        loading:0,
        jk_total:jk_total,
        paymentList: paymentList,
        is_read_count2:is_read_count2,
        is_read_count3:is_read_count3
      });
      wx.hideLoading();
    });
  },
  /**
   * 未结订单列表
   */
  nosettle: function () {
    var that = this;
    if(that.data.limit==limit_test && that.data.loading==1){
      wx.showLoading({
        title:'加载中...'
      });
    };
    var start_time=0;
    var end_time = 0;
    if(that.data.limit==limit_test && that.data.loading==1){
      wx.showLoading({
        title:'加载中...'
      });
    };
    if(that.data.screen_area_index>-1){   //时间段
      start_time = that.data.area_start;
      end_time = that.data.area_end;          
    }else if(that.data.screen_area_index==-1){   //具体时间
      if(that.data.start_time!=0){
        start_time=that.data.start_time;
        end_time =that.data.end_time;
      }; 
    };
    if(that.data.screen_area_index>-1 || that.data.screen_area_index==-1){
      var start_time_init = new Date(start_time);
      var end_time_init = new Date(end_time+3600000*24);
      start_time=start_time_init.getFullYear()+ '-' +(start_time_init.getMonth() + 1)+ '-' + start_time_init.getDate();
      end_time=end_time_init.getFullYear()+ '-' +(end_time_init.getMonth() + 1)+ '-' + end_time_init.getDate(); 
    };   
    app.AppHttp('api/Order/ClientOrderInfo', { 
      openid: app.globalData.openid,
      supplier_id: that.data.id,
      start_time:start_time,  //开始时间
      end_time: end_time,   //结束时间
      limit:that.data.limit,
      select_type:that.data.active==-1?'all':'no_all'
    }, function (res) {
      console.log(JSON.stringify(res.data));
      var init_list=res.data.list;
      var show_total_num=0;
      var order_list={};
      var is_read_count1=0;
      for(var i=0;i<init_list.length;i++){
        if(init_list[i].pay_orders==1){
          is_read_count1++;
        };
        if(order_list[init_list[i].time]){
          order_list[init_list[i].time]['xj']= order_list[init_list[i].time]['xj']+init_list[i].money*1;
          show_total_num=show_total_num+init_list[i].money*1;
          order_list[init_list[i].time]['list'].push(init_list[i]); 
        }else{
          var today_arr=today.split('-');
          var str11=today_arr[0]*1;
          var str12=today_arr[1]*1;
          var str13=today_arr[2]*1;
          var init_list_arr=init_list[i].time.split('-');
          var str21=init_list_arr[0]*1;
          var str22=init_list_arr[1]*1;
          var str23=init_list_arr[2]*1;
          order_list[init_list[i].time]={};
          order_list[init_list[i].time]['noyear']=init_list[i].time.substr(5);
          if(str11==str21 && str12==str22 && str13==str23){
            order_list[init_list[i].time]['istoday']='今天';
          }else{
            var week_list=['日','一','二','三','四','五','六'];
            order_list[init_list[i].time]['istoday']='星期'+week_list[new Date(init_list[i].time).getDay()];
          };
          order_list[init_list[i].time]['xj']=init_list[i].money*1;
          show_total_num=show_total_num+init_list[i].money*1;
          order_list[init_list[i].time]['list']=[];
          order_list[init_list[i].time]['list'].push(init_list[i]);
        }
      };
      that.setData({
        loading:0,
        order_list:order_list,
        show_total_num:show_total_num,
        list: res.data.list,
        is_read_count1:is_read_count1
      });
      wx.hideLoading();
    })
  },
  // 显示全部未结单
  show_all_ck:function(){
    this.setData({
      limit:999999,
      loading:1
    }); 
    this.nosettle();  
  },
  // 去送货单页面
  todingdancundi:function(e){
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: 'order_detial/order_detial?id=' + id+'&is_zi_cai='+this.data.is_zi_cai
    });
  },
  // 去结款单详情页面
  tomoney_count:function(e){
    var id = e.currentTarget.dataset.id;
    var client_id = this.data.rightDatas.id
    wx.navigateTo({
      url: 'money_count/money_count?id=' + id + "&client_id=" + client_id+'&is_zi_cai='+this.data.is_zi_cai
    });
  },
  // 单选
  checkboxMerge:function(e){
    var order_list = this.data.order_list;
    var index = e.currentTarget.dataset.index; //时间分类索引
    var eal = e.currentTarget.dataset.eal; //订单索引
    var shop_ids = this.data.shop_ids; //选中的id数组
    var is_checked = this.data.is_checked;  //单选是否选中
    var isclasscheck = this.data.isclasscheck; //类选是否选中
    var id = e.currentTarget.dataset.id; //订单id
    var price=e.currentTarget.dataset.price; //订单价格
    var total_money = this.data.total_money*1;
    if (is_checked[id] == true) {
      var eal = shop_ids.indexOf(id);
      shop_ids.splice(eal, 1);
      is_checked[id] = false; 
      total_money -= parseFloat(price);     
    } else {
      shop_ids.push(id);    
      is_checked[id] = true;
      total_money += parseFloat(price);
    };
    for(var j=0;j<order_list[index]['list'].length;j++){
      if (!is_checked[order_list[index]['list'][j].id]) {
        isclasscheck[index] = false
        break;
      } else {
        isclasscheck[index] = true
      }
    };
    if (shop_ids.length == this.data.list.length) {
      this.setData({
        isChooseAll: true,
        is_checked: is_checked,
        checkCount: shop_ids.length,
        isclasscheck: isclasscheck,
        shop_ids: shop_ids,
        total_money: total_money.toFixed(2)
      })
    } else {
      this.setData({
        isChooseAll: false,
        is_checked: is_checked,
        checkCount: shop_ids.length,
        isclasscheck: isclasscheck,
        shop_ids: shop_ids,
        total_money: total_money.toFixed(2)
      })
    };
  },
  // 类选
  checkedboxclass:function(e){
    var order_list = this.data.order_list;
    var shop_ids = this.data.shop_ids; //选中商品的id数组
    var index = e.currentTarget.dataset.index; //类别索引
    var isclasscheck = this.data.isclasscheck;
    isclasscheck[index] = !isclasscheck[index];
    var is_checked = this.data.is_checked;
    var total_money = this.data.total_money*1;
    if (isclasscheck[index] == true) {
      for (var i = 0; i < order_list[index]['list'].length; i++) {  
        if (!is_checked[order_list[index]['list'][i].id]) {
          shop_ids.push(order_list[index]['list'][i].id);
          total_money += parseFloat(order_list[index]['list'][i].money);   
        }
        is_checked[order_list[index]['list'][i].id] = true;
      }
    } else {
      for (var i = 0; i < order_list[index]['list'].length; i++) {
        if (is_checked[order_list[index]['list'][i].id] == true) {
          var eal = shop_ids.indexOf(order_list[index]['list'][i].id);
          shop_ids.splice(eal,1);
          total_money -= parseFloat(order_list[index]['list'][i].money);  
        }
        is_checked[order_list[index]['list'][i].id] = false;
      }
    };
    if (shop_ids.length == this.data.list.length) {
      this.setData({
        isChooseAll: true
      })
    } else {
      this.setData({
        isChooseAll: false
      })
    };
    this.setData({
      shop_ids: shop_ids,
      is_checked: is_checked,
      isclasscheck: isclasscheck,
      checkCount: shop_ids.length,
      total_money: total_money.toFixed(2)
    });
  },
  // 全选
  choose_all_but: function () {
    var order_list = this.data.order_list;
    var isclasscheck = this.data.isclasscheck;
    var is_checked = this.data.is_checked;
    var isChooseAll = !this.data.isChooseAll;
    var shop_ids = []; //选中id数组
    var total_money = 0;
    for (var i in order_list) {
      if (isChooseAll == true) {
        isclasscheck[i] = true;
        total_money += parseFloat(order_list[i].xj);
        for (var j = 0; j < order_list[i]['list'].length; j++) {
          is_checked[order_list[i]['list'][j].id] = true;
          shop_ids.push(order_list[i]['list'][j].id);
        }   
      } else {
        isclasscheck[i] = false;
        total_money=0;
        for (var j = 0; j < order_list[i]['list'].length; j++) {
          is_checked[order_list[i]['list'][j].id] = false;
          var eal = shop_ids.indexOf(order_list[i]['list'][j].id);
          shop_ids.splice(eal, 1);
        }
      }
    };
    this.setData({
      isChooseAll: isChooseAll,
      shop_ids: shop_ids,
      is_checked: is_checked,
      isclasscheck: isclasscheck,
      checkCount: isChooseAll == true ? this.data.list.length : 0,
      total_money: total_money.toFixed(2)
    });
  },
  /***
   * 生成接款单
   */
  showJieKuan: function() {
    if (this.data.checkCount == 0) {
      wx.showLoading({
        title: '请至少选择一个订单',
        duration: 500,
        mask: true //是否显示透明蒙层，防止触摸穿透，默认：false
      });
    }else{
      this.setData({
        isJieKuan: true,
        bill_name:''
      });
    }
  },
  // 输入结款单名
  input_bill_name:function(e){
    this.setData({
      bill_name: e.detail.value
    });
  },
  // 取消并关闭结款单弹窗
  cancel:function(){
    this.setData({
      isJieKuan: false
    });
  },
  // 确定并关闭结款单弹窗
  confirm: function () {
    var that = this;
    util.buttonClicked(this);  //防止重复点击
    var start_time = that.data.start_time;
    var end_time = that.data.end_time;
    if(that.data.bill_name==''){
      wx.showLoading({
        title:'请填写账单名称',
        duration:500
      });
      return;
    };
    wx.showLoading({
      title: '生成中...',
      mask: true
    });
    app.AppHttp('api/Custom/PaymentOrdersDoC', {
      openid: app.globalData.openid,
      supplier_id: that.data.id,
      order_ids: that.data.shop_ids,
      payment_name: that.data.bill_name,
      order_count: that.data.checkCount,
      total_amount: that.data.total_money,
      start_time: start_time,  //开始时间
      end_time: end_time   //结束时间
    }, function (res) {
      console.log(JSON.stringify(res.data));
      if (res.data.status == -1) {
        wx.showToast({
          title: res.data.msg
        }, 2000);
      } else {
        wx.hideLoading();
        that.setData({
          isJieKuan: false,
          isChooseAll: false, //全选
          isclasscheck: {},
          is_checked: {},   //单选
          checkCount: 0,
          shop_ids:[],
          total_money: 0,
          bill_name:'',
          loading:1,
          active:1
        });
        that.paymentList();
      }
    });
  },
  // 询价记录
  off_history:function(){
    var that = this;
    wx.showLoading({
      title:'加载中...',
    });
    app.AppHttp('api/Client/getBelongClientEnquiry', {
      client_id:app.globalData.loginInfo.id,
      supplier_id: that.data.id,
      list_type:'payment'
    }, function(res) {
      console.log(JSON.stringify(res.data));
      console.log(11111)
      that.setData({
        loading:0,
        datas:res.data.data
      });
      wx.hideLoading();
    });
  },
  // 点击进入订单详情
  itemClick: function(event) {
    var id = event.currentTarget.dataset.id;
    var index = event.currentTarget.dataset.index;
    let order_status = event.currentTarget.dataset.order_status;
    var is_cancel_apply = event.currentTarget.dataset.is_cancel_apply;
    var settitle=app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==1 || app.globalData.loginInfo.client_is_store==1?"采购单":"订单";
    var is_enquiry=event.currentTarget.dataset.is_enquiry;
    var is_created=event.currentTarget.dataset.is_created;
    var title_index=app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==1 || app.globalData.loginInfo.client_is_store==1?2:1;
    if (is_cancel_apply!=1){
      wx.navigateTo({
        url: '/pages/dingdan/order_detail/order_detail?id=' + id + "&order_status=" + order_status+ "&settitle=" + settitle+ "&title_index="+ title_index+"&is_enquiry="+is_enquiry+"&is_created="+is_created+"&d_index=" + index
      });
    }else{
      wx.showLoading({
        title: '等待对方确定',
        duration: 500
      });
    }    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.active<=0){
      this.paymentList();  
      this.nosettle();
    } else if (this.data.active >= 1 && this.data.active <= 3){
      this.setData({
        loading:1
      });
      this.nosettle();
      this.paymentList();
    }else if(this.data.active == 3){
      this.setData({
        loading:1
      });
      this.off_history();
    };   
  },
  // 打开筛选下拉
  open_screen:function(){
    var is_screen=this.data.is_screen;
    if(is_screen){
      util.hideBuyModal(this,"is_screen");
    }else{
      util.showBuyModal(this,-1);
      this.setData({
        is_screen:true
      });
    } 
  },
  // 关闭筛选下拉
  close_screen:function(){
    util.hideBuyModal(this,"is_screen");
  },
  // 选择时间段
  chose_area:function(e){
    this.setData({
      z_screen_area_index:e.currentTarget.dataset.index,
      c_start_time:0,
      c_end_time:today,
      z_start_time:0,
      z_end_time:today
    });
  },
  // 打开时间弹窗
  chose_time:function(e){
    util.showBuyModal(this);
    if(this.data.z_start_time==0){
      this.setData({
        z_start_time:today
      });
    };  
    this.setData({
      showModalStatus:true
    });
  },
  // 关闭时间弹窗
  hideBuyModal:function(){
    util.hideBuyModal(this,"showModalStatus");
  },
  // 时间周期选中效果
  bcolor: function (e) {
    var val_time=e.currentTarget.dataset.id==1?this.data.z_end_time:this.data.z_start_time;
    if(val_time!=0){
      val_time=(val_time).split('-');
      this.setData({
        value:[val_time[0] - 2010, val_time[1]-1, val_time[2] - 1]
      });
    }
    this.setData({
      time_type: e.currentTarget.dataset.id
    });
  },
  // 年、月、日改变
  bindChange: function (e) {
    util.bindchange_time(e,this,date);
  },
  // 确认并关闭选择时间周期弹窗
  queding: function () {
    if (Date.parse(new Date(this.data.z_end_time)) < Date.parse(new Date(this.data.z_start_time))){
      wx.showLoading({
        title: '时间不合理',
        duration:1000
      });
    }else{
      util.hideBuyModal(this,"showModalStatus");
      this.setData({
        z_screen_area_index:-1,
        c_start_time: this.data.z_start_time,  //开始时间
        c_end_time: this.data.z_end_time,    //结束时间
      });
    }
  },
  // 重置时间
  reset_time_but:function(){
    if(this.data.z_start_time!=0 || this.data.z_end_time!=today){
      this.setData({ 
        z_start_time:0, //选择开始时间
        z_end_time:today,   //选择结束时间,默认今天
      });
    };    
  },
  // 筛选查看
  screen_queding:function(){
    util.hideBuyModal(this,"is_screen");
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    });
    var area_start=0;  //区间开始时间
    var area_end=0;   //区间结束时间
    if(this.data.z_screen_area_index==0){  //今天
      area_start=Date.parse(new Date(today+'.00:00:00'));
      area_end=Date.parse(new Date(today+'.23:59:59'));
    }else if(this.data.z_screen_area_index==1){  //昨天
      let Day_24=new Date(Date.parse(new Date(today))-3600000);   //昨天日期
      let yesterday=Day_24.getFullYear() + "-" + (Day_24.getMonth() + 1) + "-" + Day_24.getDate();  //昨天日期
      area_start=Date.parse(new Date(yesterday+'.00:00:00'));
      area_end=Date.parse(new Date(yesterday+'.23:59:59'));
      
    }else if(this.data.z_screen_area_index==2){  //本月
      let cur_month=date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + 1;  //本月1号
      area_start=Date.parse(new Date(cur_month+'.00:00:00'));  //本月1号0点
      area_end=Date.parse(new Date(today+'.23:59:59'));
    };
    this.setData({
      screen_area_index:this.data.z_screen_area_index,
      area_start:area_start,
      area_end:area_end,
      start_time: this.data.c_start_time,
      end_time: this.data.c_end_time,
      loading:1,
      limit:limit_test
    });
    this.nosettle();
  },
  // 全部重置
  screen_reset_but:function(){
    util.hideBuyModal(this,"is_screen");
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    });
    this.setData({
      z_screen_area_index:-1,
      z_start_time:0,
      z_end_time:today,
      c_start_time:0,
      c_end_time:today,
      screen_area_index:-1,
      area_time:0,
      start_time:0,
      end_time:today,
      loading:1,
      limit:limit_test
    });
    this.nosettle();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    if (this.data.active<=0){
      this.paymentList();  
      this.nosettle();
    } else if (this.data.active >= 1 && this.data.active <= 3){
      this.setData({
        loading:1
      });
      this.nosettle();
      this.paymentList();
    }else if(this.data.active == 3){
      this.setData({
        loading:1
      });
      this.off_history();
    }; 
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }
})